<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class Shop_goodsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function __construct()
    {
        $this -> middleware('login');
    }
    
    public function index(Request $request)
    {
        //

        $num = $request -> input('num', 2);
        $keywords = $request -> input('keywords', '');

        $data = DB::table('shop_goods as c1') 
        -> select('c1.*', 'c2.name as pname')
        -> leftJoin('shop_type as c2', 'c1.tid', '=', 'c2.id')
        -> where('gname', 'like', '%'.$keywords.'%') 
        -> paginate($num);

        return view('admin.shop_goods.index', ['data' => $data, 'request' => $request -> all(), 'title' => '商品列表']);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        $data = DB::table('shop_type as c1') 
        -> select('c1.*', 'c2.name as pname', DB::raw("concat(c1.path, ',', c1.id) as sortpath"))
        -> leftJoin('shop_type as c2', 'c1.pid', '=', 'c2.id')
        -> orderBy('sortpath')
        -> get();

        foreach($data as $key => $value){
            $num = substr_count($value -> path, ',');
            $str = str_repeat('|---', $num);
            $data[$key] -> name = $str.$value -> name;
        }

        return view('admin.shop_goods.add', ['title' => '商品添加'], ['data' => $data]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        $data = $request -> except('_token');

        $this->validate($request, [
            'gname' => 'required',
            'price' => 'required|numeric',
            'cnt' => 'required|numeric',
            'gdesc' => 'required',
            'gpic' => 'image|max:2048',
        ], [
            'gname.required' => '请填写商品名称',
            'price.required' => '请认真填写价格',
            'price.numeric' => '请认真填写价格',
            'cnt.required' => '请认真填写库存',
            'cnt.numeric' => '请认真填写库存',
            'gdesc.required' => '请填写商品描述',
            'pic.image' => '请上传一张商品图片',
            'pic.max' => '图片最大2M',
        ]);

        if($request -> file('gpic') -> isValid())
        {
           // 处理头像
            $extension = $request -> file('gpic') -> getClientOriginalExtension();
            // echo $extension;
            $filename = mt_rand(10000000, 99999990).'.'.$extension;
            $dir = './uploads/avatar/'; 
            $request -> file('gpic') -> move($dir, $filename);

            $data['gpic'] = '/uploads/avatar/'.$filename;
        }else
        {
            $data['gpic'] = '/uploads/avatar/default.jpg';
        }

        $time = date('Y-m-d H:i:s');
        $data['created_at'] = $time;
        $data['updated_at'] = $time;

        $res = DB::table('shop_goods') -> insert($data);
        if($res)
        {
            return redirect('/admin/shop_goods') -> with(['info' => '添加成功']);
        }else
        {
            return back() -> with(['info' => '添加失败']);
        }        
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //

         $data = DB::table('shop_type as c1') 
        -> select('c1.*', 'c2.name as pname', DB::raw("concat(c1.path, ',', c1.id) as sortpath"))
        -> leftJoin('shop_type as c2', 'c1.pid', '=', 'c2.id')
        -> orderBy('sortpath')
        -> get();

        $cateData = DB::table('shop_goods') -> where('id', $id) -> first();


        foreach($data as $key => $value){
            $num = substr_count($value -> path, ',');
            $str = str_repeat('|---', $num);
            $data[$key] -> name = $str.$value -> name;
        }

        return view('admin.shop_goods.edit', ['title' => '编辑分类'], ['data' => $data, 'cateData' => $cateData]);
    }

     public function update(Request $request, $id)
    {

        //$data = $request -> except('_token', '_method', 'pid');
        $data = $request -> except('_token', '_method');
        
        if($request -> file('gpic') -> isValid())
        {
           // 处理头像
            $extension = $request -> file('gpic') -> getClientOriginalExtension();
            // echo $extension;
            $filename = mt_rand(10000000, 99999990).'.'.$extension;
            $dir = './uploads/avatar/'; 
            $request -> file('gpic') -> move($dir, $filename);

            $data['gpic'] = '/uploads/avatar/'.$filename;

            // 获取原来的图片
            $oldPic = DB::table('shop_goods') -> where('id', $id) -> first() -> gpic;
            if(!empty($oldPic))
            {
                if($oldPic != '/uploads/avatar/default.jpg')
                {
                    if(file_exists('.'.$oldPic))
                    {
                        unlink('.'.$oldPic);
                    }
                }
            }
        }else
        {
            $data['gpic'] = '/uploads/avatar/default.jpg';
        }

        $time = date('Y-m-d H:i:s');
        $data['updated_at'] = $time;

        $res = DB::table('shop_goods') ->where('id', $id) -> update($data);

        if($res)
        {
            return redirect('/admin/shop_goods') -> with(['info' => '编辑成功']);
        }else
        {
            return back() -> with(['info' => '编辑失败']);
        }

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        $res = DB::table('shop_goods') -> where('id', $id) -> delete();

        if($res)
        {
            return redirect('/admin/shop_goods') -> with(['info' => '删除成功']);
        }else
        {
            return back() -> with(['info' => '删除失败']);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

}
